<template>
  <div style="margin-top:20px; text-align:right">
    <!-- 权限点数据展示 -->
    <el-tree
      ref="permTree"
      :data="list"
      :props="{ label: 'name' }"
      default-expand-all
      show-checkbox
      check-strictly
      node-key="id"
    />
    <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
    <el-button size="small" @click="hCancel">取消</el-button>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permisson'
import { tranListToTreeData } from '@/utils'
import { assignPerm, getRoleDetailById } from '@/api/roles'
export default {
  name: 'VueAdminTemplateAssignPermission',
  props: {
    roleId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: [] // 存储权限数据
    }
  },
  created() {
    this.loadPermissions()
    this.loadRoleDetail()
  },
  methods: {
    hCancel() {
      // 通过父组件去关闭弹层
      this.$emit('close')
    },
    async loadPermissions() {
      const res = await getPermissionList().catch(e => e)
      if (!res.success) return
      this.list = tranListToTreeData(res.data)
    },
    async  loadRoleDetail() {
      const res = await getRoleDetailById(this.roleId).catch(e => e)
      console.log(res)
      console.log('获取角色现有的权限', res.data.permIds)
      if (!res.success) return
      this.$refs.permTree.setCheckedKeys(res.data.permIds)
    },
    async hSubmit() {
      // 用户点击确定
      // 获取用户勾选的权限 id 列表
      const permIds = this.$refs.permTree.getCheckedKeys()
      // console.log(result)
      // 发请求 id: 角色 id
      const res = await assignPerm({ id: this.roleId, permIds }).catch(e => e)
      // 提醒用户
      if (!res.success) return this.$message.error(res.message)
      this.$message.success(res.message)

      // 关闭 dialog
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
